package com.lzx.httpclient;

import java.io.OutputStream;
import java.nio.charset.Charset;

public class StringBody extends AbstractBody {

	private String name;

	private String value;
	
	private String charset;

	public StringBody(String name, String value) {
		this(name, value, "text/plain", "utf-8");
	}
	
	
	public StringBody(String name, String value, String mimeType) {
		this(name, value, mimeType, "utf-8");
	}
	
	public StringBody(String name, String value, String mimeType, String charset) {
		
		super(mimeType);
		this.name = name;
		this.value = value;
		this.charset = charset;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public void writeTo(OutputStream os, boolean writeContent) {
		try{
			
			
			
//			-----------------------------98942870323811
//			Content-Disposition: form-data; name="name"
//				
//			1 
		StringBuilder sb = new StringBuilder();
		sb.append("--" + this.boundary + LR);		
		sb.append("Content-Disposition: form-data; name=\"" + this.name + "\"" + LR);
		sb.append(LR);
		
		os.write(sb.toString().getBytes());
		
		if(writeContent) {
			os.write(this.value.getBytes(Charset.forName(charset)));
			os.write(LR.getBytes());
		}		
	
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	@Override
	public long getContentLength() {
		// TODO Auto-generated method stub
		return this.value.getBytes(Charset.forName(charset)).length;
	}

}
